package com.aliyun.messagemgt.service;

import com.aliyun.messagemgt.common.dto.send.*;
import com.aliyun.messagemgt.common.enums.ChannelTypeEnum;
import com.aliyun.messagemgt.common.exception.BaseException;
import com.aliyun.messagemgt.pojo.vo.MailSendInfoVO;
import com.aliyun.messagemgt.sendplugin.SendStrategy;
import com.aliyun.messagemgt.sendplugin.SendStrategyFactory;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 邮件渠道
 *
 * @author byp
 * @date 2020/5/18
 */
@Service
public class MailSendStrategy implements SendStrategy, InitializingBean {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private MailService mailService;

    @Override
    public void afterPropertiesSet() {
        SendStrategyFactory.register(ChannelTypeEnum.MAIL.getType(), this);
    }

    @Override
    public void sendMessage(PushChannelInfo pushChannelInfo, MsgRecordVO msgRecordVO) {


        List<Receiver> receivers = msgRecordVO.getReceivers();
        if (CollectionUtils.isEmpty(receivers)) {
            logger.info("触发短时间重复发送抑制。");
            return;
        }
        List<MsgBody> msgBodies = msgRecordVO.getContents();
        String title = msgRecordVO.getMsgTitle();
        String subject = msgRecordVO.getSubject();
        if (StringUtils.isBlank(subject)) {
            logger.error("邮件消息主题[messageSubject]为空");
            throw new BaseException("邮件消息主题[messageSubject]为空");
        }
        String attachmentAddress = msgRecordVO.getAttachmentAddress();

        String[] toUser = receivers.stream().map(Receiver::getReceiverEmail).filter(value -> StringUtils.isNotBlank(value)).toArray(String[]::new);
        if (ArrayUtils.isEmpty(toUser)) {
            logger.error("邮件接收人为空");
            throw new BaseException("邮件接收人为空");
        }
        MailSendInfoVO mailSendInfoVO = new MailSendInfoVO();
        mailSendInfoVO.setTitle(title);
        mailSendInfoVO.setSubject(subject);
        mailSendInfoVO.setFromUser(from);
        mailSendInfoVO.setToUser(toUser);
        mailSendInfoVO.setContent(msgBodies.get(0).getContent());
        mailSendInfoVO.setAttachmentAddress(attachmentAddress);

        boolean send = mailService.sendAttachmentsMail(pushChannelInfo, mailSendInfoVO);
        List<MsgMiddleResult> results = msgRecordVO.getResults();
        if (send) {
            MsgMiddleResult msgMiddleResult = new MsgMiddleResult().setPushResultCode(1)
                    .setPushResultDescription("邮件渠道消息推送成功")
                    .setReceivers(msgRecordVO.getReceivers());
            results.add(msgMiddleResult);
        } else {
            MsgMiddleResult msgMiddleResult = new MsgMiddleResult().setPushResultCode(2)
                    .setPushResultDescription("邮件渠道消息推送失败")
                    .setReceivers(msgRecordVO.getReceivers());
            results.add(msgMiddleResult);
        }
    }
}
